<?php
namespace App\Http\Controllers\Api;


use App\Api\Helpers\Push\Sms;
use App\Helpers\Push\Messages\ChangePasswordMessage;
use Carbon\Carbon;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Laravel\Passport\Client;
use Laravel\Socialite\Two\InvalidStateException;
use Socialite;
use App\Models\User;
use Illuminate\Http\Request;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Validator;


class AuthenticateController extends ApiController
{

    use AuthenticatesUsers;

    public function __construct()
    {

        $this->middleware('auth:api')->only([
            'logout'
        ]);
    }

    public function username()
    {
        return 'phone';
    }


    // 发送重置密码验证码

    /**
     * @api {post} /seedCode 发送重置密码验证码
     * @apiName Auth seedCode
     * @apiGroup Auth
     *
     *
     * @apiParam {string} phone 手机号
     *
     * @apiVersion 1.0.0
     *
     * @apiSampleRequest /api/seedCode
     */
    public function seedCode(Request $request){

        $this->validate($request,[
            'phone' => 'required|min:11|max:11'
        ]);

        $phone = $request->phone;

        $code = random_int(10000,99999);
        $message = new ChangePasswordMessage($code);

        Sms::make()->send($phone,$message);

        Cache::put($phone.'code', $code,15);
        Cache::put($phone.'attempts',3,15);


        return $this->message('发送成功');

    }

    /**
     * @api {post} /auth/login 网站登录接口
     * @apiName Auth login
     * @apiGroup Auth
     *
     * @apiParam {String} phone 用户的手机号
     * @apiParam {String} password 用户的密码
     *
     * @apiVersion 2.0.0
     *
     * @apiSampleRequest /api/auth/login
     *
     * @apiSuccessExample {json} Success-Response:
     *
     *  {
     *       "token_type": "Bearer",
     *       "expires_in": 1295999,
     *       "access_token": "eyJ0eXAiOiJKV1Q",
     *       "refresh_token": "def5020039a665c1a0"
     *   }
     *
     */
    public function login(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'phone'    => 'required|exists:user',
            'password' => 'required|between:5,32',
        ]);

        if ($validator->fails()) {
            $request->request->add([
                'errors' => $validator->errors()->first(),
                'code' => 401,
            ]);
            return $this->sendFailedLoginResponse($request);
        }

        $credentials = $this->credentials($request);

        if ($this->guard('api')->attempt($credentials, $request->has('remember'))) {
            return $this->sendLoginResponse($request);
        }

        return $this->setStatusCode(401)->failed('用户名或密码不正确');
    }



    /**
     * @api {delete} /auth/logout 退出登录
     * @apiGroup Auth
     * @apiPermission none
     *
     * @apiHeaderExample {json} Header-Example:
     *    {
     *       "Authorization" : "Bearer {token}"
     *    }
     * @apiVersion 0.0.0
     * @apiSuccessExample {json} Success-Response:
     *     {
     *           "status": "success",
     *           "code": 200,
     *           "message": "退出登录成功",
     *     }
     */

    public function logout(Request $request)
    {

        if (Auth::guard('api')->check()){

            Auth::guard('api')->user()->token()->revoke();

        }

        return $this->message('退出登录成功');

    }

    /**
     * @api {get} /oauth/redirect/driver/:driver 网页端第三方登录
     * @apiGroup Auth
     * @apiPermission none
     *
     * @apiParam {String} driver QQ登录=>qq,微信登录=>wechat,weibo=>新浪微博登录
     *
     */
    public function redirectToProvider($driver) {

        if (!in_array($driver,['qq','wechat'])){

            throw new NotFoundHttpException;
        }

        return Socialite::driver($driver)->redirect();
    }


    // 回调
    public function handleProviderCallback($driver) {

        try{
            $user = Socialite::driver($driver)->user();
        }catch (InvalidStateException $e){

            return redirect()->route('oauth.redirect','qq');

        }



        $openId = $user->id;

        $db_user = User::where('qqUnionId',$openId)->first();

        if (empty($db_user)){

            $db_user = User::forceCreate([
                'phone' => '',
                'qqUnionId' => $openId,
                'nickname' => $user->nickname,
                'qqName' => $user->nickname,
                'head' => $user->avatar,
                'sex' => ($user->gender == '男') ? 1 : 0,
                'register_time' => time(),
                'last_time' => time()
            ]);

        }

        $createToken = $db_user->createToken($openId);

        $createToken->token->expires_at = Carbon::now()->addDays(15);
        $createToken->token->save();

        $token = $createToken->accessToken;

        return view('thirdLogin',compact('token'));

    }


    //调用认证接口获取授权码
    protected function authenticateClient(Request $request)
    {
        $credentials = $this->credentials($request);

        $password_client = Client::query()->where('password_client',1)->latest()->first();

        $request->request->add([
            'grant_type' => 'password',
            'client_id' => $password_client->id,
            'client_secret' => $password_client->secret,
            'username' => $credentials['phone'],
            'password' => $credentials['password'],
            'scope' => ''
        ]);

        $proxy = Request::create(
            'oauth/token',
            'POST'
        );

        $response = \Route::dispatch($proxy);

        return $response;
    }



    protected function authenticated(Request $request)
    {
        return $this->authenticateClient($request);
    }

    protected function sendLoginResponse(Request $request)
    {
        $this->clearLoginAttempts($request);

        return $this->authenticated($request);
    }

    protected function sendFailedLoginResponse(Request $request)
    {
        $msg = $request['errors'];
        $code = $request['code'];
        return $this->setStatusCode($code)->failed($msg);
    }



}